package com.siraz.questica;

import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Random;

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.siraz.questica.entities.items.Item;

public class QuesticaGame extends Game {
	private OrthographicCamera camera;
	private SpriteBatch batch;
	private Texture groundTexture;
	private TextureRegion groundTextures[];
	
	private int[][] map = new int[10][10];
	
	Player player;
	
	@Override
	public void create() {		
		//float w = Gdx.graphics.getWidth();
		//float h = Gdx.graphics.getHeight();
		
		Random rand = new Random();
		
		player = new Player();
		camera = new OrthographicCamera(960/3, 640/3);
		batch = new SpriteBatch();
		
		groundTextures = new TextureRegion[4];
		groundTexture = new Texture(Gdx.files.internal("data/forrestfloor1.png"));
		TextureRegion tmp[][] = TextureRegion.split(groundTexture, 40, 40);
		groundTextures[0] = tmp[0][0];
		groundTextures[1] = tmp[1][0];
		groundTextures[2] = tmp[0][1];
		groundTextures[3] = tmp[1][1];
		
		for(int i = 0; i < 10; i++) {
			for(int j = 0; j < 10; j++) {
				map[i][j] = rand.nextInt(4);
			}
		}
		
		XMLEncoder x;
		ArrayList<Item> itemList = new ArrayList<Item>();
		itemList.add(new Item("Thing", 0, 25, 30, true));
		try {
			File file = new File("data/items");
			if(!file.exists())
				file.mkdirs();
			x = new XMLEncoder(new BufferedOutputStream(new FileOutputStream("data/items.xml")));
			x.writeObject(itemList);
			x.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("location not found: " + Gdx.files.getLocalStoragePath());
		}
	}

	@Override
	public void dispose() {
		batch.dispose();
		groundTexture.dispose();
	}

	@Override
	public void render() {		
		Gdx.gl.glClearColor(1, 1, 1, 1);
		Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
		
		batch.setProjectionMatrix(camera.combined);
		batch.begin();
		
		for(int i = -5; i < 5; i++) {
			for(int j = -5; j < 5; j++) {
				batch.draw(groundTextures[map[i+5][j+5]], i*40, j*40);
			}
		}
		
		player.draw(batch);
		batch.end();
	}

	@Override
	public void resize(int width, int height) {
	}

	@Override
	public void pause() {
	}

	@Override
	public void resume() {
	}
}
